<?php
//http://ec2-184-73-101-215.compute-1.amazonaws.com/psych/getFieldListing.php?field=regionName&constraint1=Media%20Market
require_once("databaseCreds.php");
require_once("connectDB.php");

$fld=$_GET["field"];
$con1= isset($_GET["constraint1"]) ? $_GET["constraint1"] : "";
if (preg_match("/^[A-z ]*$/i",$con1)<1){
  die("Error: Illegal character in constraint1: " . $con1);
}
if($fld=="") {
  die("Error: no field specified");
} else {
  $sql=getSQL($fld,$con1);
  if($sql=="") {
    //some error
  } else {
      $result = mysql_query($sql);
       if (!$result) {
          die('Invalid query: ' . mysql_error() . '<br/>' . $sql);
      } else {
        print_result($result);    
      }
  }
}

function getSQL($fld,$con1) {
  $sql="";
  if ($fld=="state") {
    $sql="select distinct(state) from region order by state;";
  } else if ($fld=="shockType") {
    $sql="select distinct(name) from shockType order by name;";
  } else if ($fld=="regionType") {
    $sql="select distinct(type) from region where type <> 'None' union select distinct(type) from regionTypeExtra order by type;";
  } else if ($fld=="regionName") {
    if($con1=="City") {//should have a better check for voter table field rather than region
      $sql="select distinct(city) from voter order by city";
    } else {
      $sql="select distinct(name) from region";
      if (strlen($con1)>0) {
        $sql.=" where type='$con1'";
      } else {
        $sql.=" where type <> 'None'";
      }
      $sql.=" order by name;";
    }
  } else if ($fld=="measurementType") {
    $sql="select distinct(name) from measurementType order by name;";
  } else if ($fld=="metric") {
    $sql="select distinct(name) from metric order by name;";
  } else if ($fld=="onOrBetween") {
    $sql="select 'on' union select 'between';";
  }
  else {
    die("Illegal Field: " & $fld);
  }
  return($sql);
}

function print_result($result) {
    while ($row = mysql_fetch_array($result)) {
      print($row[0] . "|");
    }
}

?>